﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;

namespace WeeklyEmailReporting
{
	public class HtmlTemplateUtility
	{
		public static string GetHtmlReportFromTemplate(DataRow studentRow, DataTable gradeTable)
		{
			string htmlReport = "";

			string emailTemplate;
			using (
				var sr =
					new StreamReader(System.Web.HttpContext.Current.Server.MapPath("~/EmailTemplates\\WeeklyProgressReport.htm")))
			{
				emailTemplate = sr.ReadToEnd();
                emailTemplate = emailTemplate.Replace("%WeeklyProgressReportLogoImageFileName%", System.Configuration.ConfigurationManager.AppSettings["WeeklyProgressReportLogoImageFileName"]);
			}

			string tableRowTemplate;
			using (
				var sr = new StreamReader(System.Web.HttpContext.Current.Server.MapPath("~/EmailTemplates\\WeeklyProgressReportTableRow.htm")))
			{
				tableRowTemplate = sr.ReadToEnd();
			}


			htmlReport = emailTemplate.Replace("%%FirstName%%", studentRow["FIRST_NAME"].ToString())
				.Replace("%%LastName%%", studentRow["LAST_NAME"].ToString())
				.Replace("%%GradeLevel%%", studentRow["GRADE_LEVEL"].ToString())
				.Replace("%%CurrentDate%%", DateTime.Today.ToShortDateString());

			if (gradeTable.Rows.Count > 0)
			{
				string tableRowsString = "";

				foreach (DataRow gradeRow in gradeTable.Rows)
				{
					//fill template

					tableRowsString += tableRowTemplate.Replace("%%CourseName%%", gradeRow["COURSE_NAME"].ToString())
						.Replace("%%Teacher%%", gradeRow["TEACHER"].ToString())
						.Replace("%%TeacherPhone%%", gradeRow["TEACHER_PHONE"].ToString())
						.Replace("%%TeacherEmail%%", gradeRow["EMAIL_ADDR"].ToString())
						.Replace("%%Grade%%", gradeRow["GRADE"].ToString())
						.Replace("%%Percentage%%", gradeRow["PERCENTAGE"].ToString())
						.Replace("%%TotalMinutesPrevousWeek%%", gradeRow["TOTAL_MINUTES_PREVIOUS_WEEK"].ToString())
						.Replace("%%LastLoginDate%%", gradeRow["LAST_LOGIN_DATE"].ToString());
				}
				htmlReport = htmlReport.Replace("%%WeeklyProgressReportTableRow%%", tableRowsString);
			}

			return htmlReport;
		}
	}
}
